package com.oswift.cms.web.backstage;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.AreaBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.MemberBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.UserGroupBean;
import com.oswift.cms.service.IAreaService;
import com.oswift.cms.service.IMemberService;
import com.oswift.cms.service.IUserGroupService;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.ReceptionConstant;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.CipherUtil;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class MemberAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(MemberAction.class);

    /**
     * spring 注入
     */
    @Resource
    private IMemberService memberService;

    /**
     * spring 注入
     */
    @Resource
    private IUserGroupService userGroupService;

    /**
     * spring注入AreaServiceImpl对象
     */
    @Resource
    private IAreaService areaService;

    /**
     *
     * 会员列表
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getMemberList", method = RequestMethod.GET)
    public ModelAndView getMemberList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(request.getParameter("pageNum")))
            {
                pageNum = Integer.valueOf(request.getParameter("pageNum"));
            }
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            PageBean<MemberBean> pageBean = memberService.getMemberList(
                    companyId, pageNum, pageRecordNum);

            // 设置每页显示多少天数据
            pageBean.setPageRecordNum(this.pageRecordNum);
            mv = new ModelAndView(PageName.MEMBERLIST);
            mv.addObject("pageBean", pageBean);
        }
        catch (PlatException e)
        {
            log.error("The method of getMemberList is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of getMemberList is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 加载会员新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddMember", method = RequestMethod.GET)
    public ModelAndView loadAddMember(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            mv = new ModelAndView(PageName.MEMBER);
            int companyId = this.getAdmin(request).getCompanyID();
            List<UserGroupBean> list = userGroupService
                    .getUserGroupByCompanyId(companyId);
            List<AreaBean> areas = areaService.getArea(Field.Area.PROVINCE);
            mv.addObject(METHOD, METHOD_ADD);
            mv.addObject("list", list);
            mv.addObject("areas", areas);
        }
        catch (PlatException e)
        {
            log.error("The method of loadAddMember is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadAddMember is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 加载会员修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateMember", method = RequestMethod.GET)
    public ModelAndView loadUpdateMember(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }

            MemberBean bean = memberService.getMemberDetail(Long.valueOf(id));
            mv = new ModelAndView(PageName.MEMBER);
            int companyId = this.getAdmin(request).getCompanyID();
            List<UserGroupBean> list = userGroupService
                    .getUserGroupByCompanyId(companyId);
            List<AreaBean> areas = areaService.getArea(Field.Area.PROVINCE);
            mv.addObject(METHOD, METHOD_UPDATE);
            mv.addObject("list", list);
            mv.addObject("areas", areas);
            mv.addObject("bean", bean);
        }
        catch (PlatException e)
        {
            log.error("The method of loadUpdateMember is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadUpdateMember is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 新增会员
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addMember", method = RequestMethod.POST)
    @ResponseBody
    public Object addMember(HttpServletRequest request)
    {
        MessageBean messBean = null;
        try
        {
            messBean = getPageData(request, METHOD_ADD);
            if (!PageCode.COMMON_SUCCESS.equals(messBean.getCode()))
            {
                return messBean;
            }
            int companyId = this.getAdmin(request).getCompanyID();
            boolean isSuccess = memberService.addMember((MemberBean) messBean
                    .getObjContent(), companyId);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.MEMBER_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of addMember is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of addMember is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 修改会员
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updateMember", method = RequestMethod.POST)
    @ResponseBody
    public Object updateMember(HttpServletRequest request)
    {
        MessageBean messBean = null;
        try
        {
            messBean = getPageData(request, METHOD_UPDATE);
            if (!PageCode.COMMON_SUCCESS.equals(messBean.getCode()))
            {
                return messBean;
            }

            boolean isSuccess = memberService
                    .updateMember((MemberBean) messBean.getObjContent());
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.MEMBER_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of updateMember is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of updateMember is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 会员详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getMemberDetail", method = RequestMethod.GET)
    public ModelAndView getMemberDetail(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }
            mv = new ModelAndView(PageName.MEMBERDETAIL);
            MemberBean bean = memberService.getMemberDetail(Long.valueOf(id));
            mv.addObject("bean", bean);
        }
        catch (PlatException e)
        {
            log.error("The method of getMemberDetail is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of getMemberDetail is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 删除会员
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delMember", method = RequestMethod.POST)
    @ResponseBody
    public Object delMember(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String ids = request.getParameter("ids");
            if (StringUtil.isEmpty(ids))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            int rows = 0;
            String arrayId[] = ids.split(Field.COMMA);
            for (String id : arrayId)
            {
                boolean isSuccess = memberService.delMember(Long.valueOf(id));
                if (isSuccess)
                {
                    rows++;
                }
            }

            if (rows > 0)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.MEMBER_DEL_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_DEL_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of delMember is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of delMember is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 获取页面数据
     *
     * @author zhuou
     * @throws PlatException
     *             公共异常
     */
    private MessageBean getPageData(HttpServletRequest request, String method)
        throws PlatException
    {
        MessageBean messBean = new MessageBean();
        messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
        messBean.setContent(ResourceManager
                .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));

        String userId = request.getParameter("userId");
        String groupId = request.getParameter("groupId");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String question = request.getParameter("question");
        String answer = request.getParameter("answer");
        String trueName = request.getParameter("trueName");
        String email = request.getParameter("email");
        String officePhone = request.getParameter("officePhone");
        String mobile = request.getParameter("mobile");
        String homePhone = request.getParameter("homePhone");
        String qq = request.getParameter("qq");
        String birthday = request.getParameter("birthday");
        String cardType = request.getParameter("cardType");
        String nativePlace = request.getParameter("nativePlace");
        String nation = request.getParameter("nation");
        String sex = request.getParameter("sex");
        String marriage = request.getParameter("marriage");
        String education = request.getParameter("education");
        String graduateFrom = request.getParameter("graduateFrom");
        String interestsOfLife = request.getParameter("interestsOfLife");
        String interestsOfCulture = request.getParameter("interestsOfCulture");
        String interestsOfAmusement = request
                .getParameter("interestsOfAmusement");
        String interestsOfSport = request.getParameter("interestsOfSport");
        String interestsOfOther = request.getParameter("interestsOfOther");
        String income = request.getParameter("income");
        String family = request.getParameter("family");
        String company = request.getParameter("company");
        String department = request.getParameter("department");
        String position = request.getParameter("position");
        String companyAddress = request.getParameter("companyAddress");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String district = request.getParameter("district");
        String zipCode = request.getParameter("zipCode");
        String address = request.getParameter("address");
        String enableResetPassword = request
                .getParameter("enableResetPassword");
        String faceHeight = request.getParameter("faceHeight");
        String faceWidth = request.getParameter("faceWidth");
        String homepage = request.getParameter("homepage");
        String idCard = request.getParameter("idCard");
        String userFace = request.getParameter("userFace");

        // 这些字段是不容许为空的
        if (StringUtil.isEmpty(groupId) || StringUtil.isEmpty(userName)
                || StringUtil.isEmpty(trueName))
        {
            return messBean;
        }

        MemberBean bean = new MemberBean();

        // 如果是新增，哪些字段不可以为空
        if (METHOD_ADD.equals(method))
        {
            if (StringUtil.isEmpty(userPassword))
            {
                return messBean;
            }
            bean.setUserPassword(CipherUtil.generatePassword(userPassword));
        }

        // 如果是修改，哪些字段不可以为空
        if (METHOD_UPDATE.equals(method))
        {
            if (StringUtil.isEmpty(userId))
            {
                return messBean;
            }
            bean.setUserId(Long.valueOf(userId));
        }

        bean.setAddress(address);
        bean.setAnswer(answer);
        if (!StringUtil.isEmpty(birthday))
        {
            bean.setBirthday(TimeUtil.stringToDate(birthday,
                    TimeUtil.ISO_DATE_NOSECOND_FORMAT));
        }
        if (!StringUtil.isEmpty(cardType))
        {
            bean.setCardType(Integer.valueOf(cardType));
        }
        else
        {
            // 默认
            bean.setCardType(ReceptionConstant.MemberConstant.CardType.IDCARD);
        }
        bean.setCity(city);
        bean.setCompany(company);
        bean.setCompanyAddress(companyAddress);
        bean.setCreateTime(new Date());
        bean.setDepartment(department);
        bean.setDistrict(district);
        bean.setEducation(education);
        bean.setEmail(email);
        boolean bEnableResetPassword = true;
        if (Field.FALSE.equals(enableResetPassword))
        {
            bEnableResetPassword = false;
        }
        bean.setEnableResetPassword(bEnableResetPassword);
        if (!StringUtil.isEmpty(faceHeight))
        {
            bean.setFaceHeight(Integer.valueOf(faceHeight));
        }
        if (!StringUtil.isEmpty(faceWidth))
        {
            bean.setFaceWidth(Integer.valueOf(faceWidth));
        }
        bean.setFamily(family);
        bean.setHomepage(homepage);
        bean.setHomePhone(homePhone);
        bean.setIdCard(idCard);
        bean.setIncome(income);
        bean.setInterestsOfAmusement(interestsOfAmusement);
        bean.setInterestsOfCulture(interestsOfCulture);
        bean.setInterestsOfLife(interestsOfLife);
        bean.setInterestsOfOther(interestsOfOther);
        bean.setInterestsOfSport(interestsOfSport);
        if (!StringUtil.isEmpty(marriage))
        {
            bean.setMarriage(Integer.valueOf(marriage));
        }
        else
        {
            bean.setMarriage(ReceptionConstant.MemberConstant.Marriage.SECRET);
        }
        bean.setMobile(mobile);
        bean.setNation(nation);
        bean.setNativePlace(nativePlace);
        bean.setOfficePhone(officePhone);
        bean.setPosition(position);
        bean.setProvince(province);
        bean.setQq(qq);
        bean.setQuestion(question);
        bean.setRegTime(new Date());
        if (!StringUtil.isEmpty(sex))
        {
            bean.setSex(Integer.valueOf(sex));
        }
        else
        {
            bean.setSex(ReceptionConstant.MemberConstant.Sex.MALE);
        }
        bean.setStatus(ReceptionConstant.MemberConstant.Status.NORMAL);
        bean.setTrueName(trueName);
        bean.setUserExp(0);
        bean.setUserFace(userFace);
        bean.setUserName(userName);
        bean.setZipCode(zipCode);
        bean.setGraduateFrom(graduateFrom);
        bean.setGroupId(Integer.valueOf(groupId));

        messBean.setCode(PageCode.COMMON_SUCCESS);
        messBean.setObjContent(bean);
        return messBean;
    }

    public void setMemberService(IMemberService memberService)
    {
        this.memberService = memberService;
    }

    public void setUserGroupService(IUserGroupService userGroupService)
    {
        this.userGroupService = userGroupService;
    }

    public void setAreaService(IAreaService areaService)
    {
        this.areaService = areaService;
    }
}
